package com.cirnoworks.guice;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.google.inject.Injector;

public class CirnoGuiceListener implements ServletContextListener {

	static final String INJECTOR_NAME = Injector.class.getName();
	static final String CREATOR_NAME = InjectorCreator.class.getName();

	public void contextInitialized(ServletContextEvent servletContextEvent) {
		final ServletContext servletContext = servletContextEvent
				.getServletContext();
		InjectorCreator creator;
		try {
			String className = (String) servletContext
					.getInitParameter("injectorCreator");
			Class<?> clazz;
			clazz = Class.forName(className);
			creator = (InjectorCreator) clazz.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(
					"You must specify injectorCreator to a subclass of InjectorCreator.",
					e);
		}
		servletContext.setAttribute(INJECTOR_NAME, creator.createInjector());
		servletContext.setAttribute(CREATOR_NAME, creator);
	}

	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		Injector injector = (Injector) servletContext
				.getAttribute(INJECTOR_NAME);
		InjectorCreator creator = (InjectorCreator) servletContext
				.getAttribute(CREATOR_NAME);
		creator.shutdownInjector(injector);
		servletContext.removeAttribute(CREATOR_NAME);
		servletContext.removeAttribute(INJECTOR_NAME);
	}

}
